//
//  RCUserPhoneRegVerifyCodeVC.m
//  RocketProject
//
//  Created by chen jiedan on 13-8-26.
//  Copyright (c) 2013年 Rocket. All rights reserved.
//

#import "RCUserPhoneRegVerifyCodeVC.h"
#import "UIColor-Expanded.h"
#import "CommonDefines.h"
#import "IManager+RegisterRequest.h"
#import "RCPhoneVerifyDataModel.h"
#import "AppDelegate.h"
#import "RCUserPhoneRegFullfilNickVC.h"

#define MAXLENGTH 6

@interface RCUserPhoneRegVerifyCodeVC ()<IManagerDelegate,UITextFieldDelegate>{
  
}

@end

@implementation RCUserPhoneRegVerifyCodeVC{
    UITextField *_inPutFiled;
    UIButton    *_reGetBtn;
    UIButton    *_submitBtn;
    int64_t     _reReqID; //重新获取验证码
    int64_t     _subVerifyReqID;
    
    NSString *_phoneNum;
    
    NSTimer *t;
    NSInteger total;
    
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (id) initWithRegPhone:(NSString*)phone
{
    self = [super init];
    if (self) {
        _phoneNum = [phone copy];
        
    }
    return self;
}

- (void) dealloc
{
    [[IManager sharedInstance] cancelFetchDataRequestByRequestID:_reReqID];
    [[IManager sharedInstance] cancelFetchDataRequestByRequestID:_subVerifyReqID];

    [t invalidate];
    [_phoneNum release];
    [super dealloc];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    
    UILabel *noticeLabel = [[UILabel alloc] initWithFrame:CGRectMake(40, 15, 240, 12)];
    [self.view addSubview:noticeLabel];
    noticeLabel.backgroundColor = [UIColor clearColor];
    noticeLabel.textColor = [UIColor colorWithHex:0xff979797];
    noticeLabel.font = [UIFont systemFontOfSize:12];
    [noticeLabel release];
    noticeLabel.text = @"已向该手机号码发送验证码，请注意查收";
    
    UILabel *phoneNumber = [[UILabel alloc] initWithFrame:CGRectMake(40, 30, 160, 20)];
    [self.view addSubview:phoneNumber];
    phoneNumber.textColor = [UIColor colorWithHex:0xff979797];
    phoneNumber.backgroundColor = [UIColor clearColor];
    [phoneNumber release];
    phoneNumber.text = _phoneNum;
    
    UIImageView *bg1 = [[[UIImageView alloc] initWithFrame:CGRectMake(14, 50+7, 320-14*2, 47)] autorelease];
    UIImage *img1 = [UIImage imageNamed:@"form_bg1"];
    bg1.image = img1;
    [self.view addSubview:bg1];
    
    
    UILabel *phoneLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, 16, 70, 16)];
    [bg1 addSubview:phoneLabel];
    [phoneLabel setFont:[UIFont fontWithName:kFontNameLightHeiti size:16]];
    phoneLabel.textColor = [UIColor colorWithHex:0xff979797];
    
    phoneLabel.text = @"验证码";
    [phoneLabel release];
    
    
    _inPutFiled = [[UITextField alloc] initWithFrame:CGRectMake(100, 50+20, 200, 20)];
    [self.view addSubview:_inPutFiled];
    [_inPutFiled setBackgroundColor:[UIColor clearColor]];
    _inPutFiled.clearButtonMode = UITextFieldViewModeWhileEditing;
    _inPutFiled.font = [UIFont systemFontOfSize:16];
    _inPutFiled.placeholder = @"请输入6位验证码";
    //    _userNameLabel.tag = kTagUserName;
    _inPutFiled.returnKeyType = UIReturnKeyDone;
    _inPutFiled.delegate = self;
    [_inPutFiled release];
    
    _reGetBtn = [[UIButton alloc] initWithFrame:CGRectMake(14, 110, 160, 35)];
    [_reGetBtn setBackgroundImage:img1 forState:UIControlStateNormal];
    [_reGetBtn setTitle:@"重新获取验证码(60秒)" forState:UIControlStateNormal];
    _reGetBtn.titleLabel.font = [UIFont fontWithName:kFontNameLightHeiti size:13];
    [_reGetBtn setTitleColor:[UIColor colorWithHex:0xff979797] forState:UIControlStateNormal];
    [_reGetBtn addTarget:self action:@selector(reGetVerifyCode) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_reGetBtn];
    _reGetBtn.enabled = NO;
    [_reGetBtn release];
    
    _submitBtn = [[UIButton alloc] initWithFrame:CGRectMake(190, 110, 120, 35)];
    [_submitBtn setTitle:@"提交验证码" forState:UIControlStateNormal];
    [self.view addSubview:_submitBtn];
    UIImage *loginIMG = [UIImage imageNamed:@"login_btn"];
    [_submitBtn setBackgroundImage:loginIMG forState:UIControlStateNormal];
    [_submitBtn addTarget:self action:@selector(regPress:) forControlEvents:UIControlEventTouchUpInside];
    [_submitBtn release];
    
    total = 60;
     t = [NSTimer scheduledTimerWithTimeInterval: 1.0
                                                  target: self
                                                selector:@selector(onTick:)
                                                userInfo: nil repeats:YES];
    
}


-(void)onTick:(NSTimer *)timer {
    if (total == 0) {
        return;
    }
    
    total --;
    [_reGetBtn setTitle:[NSString stringWithFormat:@"重新获取验证码(%d秒)",total] forState:UIControlStateNormal];
    if (total == 0) {
        [_reGetBtn setTitle:@"重新获取验证码" forState:UIControlStateNormal];
        _reGetBtn.enabled = YES;
    }

}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//点击提交验证码按钮
- (void) regPress:(id)sender
{
    
    NSString *checkCode = [_inPutFiled.text stringByReplacingOccurrencesOfString:@" " withString:@""];

    if ([checkCode length] == MAXLENGTH) {
        _subVerifyReqID = [[IManager sharedInstance] requestPhoneNumber:_phoneNum withVerifyCode:checkCode withDelegate:self];
    }else{
        [RCAppDelegate alertWithCustomizeString:@"验证码不足六位，请正确输入"];
    }

}

//60秒到后 可重新获取验证码
- (void) reGetVerifyCode
{
    _reReqID = [[IManager sharedInstance] requestRegVerifyCodePhoneNumber:_phoneNum withDelegate:self];

}


- (void) updateViewForError:(NSError *)errorInfo withRequestId:(int64_t)requestId
{
    [RCAppDelegate alertWithCustomizeString:@"提交验证码失败"];
}


- (void) updateViewForSuccess:(IDataModel *)dataModel withRequestId:(int64_t)requestId
{
    if ([dataModel isKindOfClass:[RCPhoneVerifyDataModel class]]) {
        //重新获取验证码
        RCPhoneVerifyDataModel *model = (RCPhoneVerifyDataModel *)dataModel;
        if (model.errorNO == RCErrorTypeNoError) {
            total = 60;
            _reGetBtn.enabled = NO;
        }else{
            [RCAppDelegate alertWithCustomizeString:model.errorMsg];
        }
    }else if ([dataModel isKindOfClass:[RCPhoneSubmitCheckCodeDataModel class]]){
        //提交验证码
        RCPhoneSubmitCheckCodeDataModel *model = (RCPhoneSubmitCheckCodeDataModel *)dataModel;
        if (model.errorNO == RCErrorTypeNoError) {
            RCUserPhoneRegFullfilNickVC *vc = [[RCUserPhoneRegFullfilNickVC alloc] initWithRegPhone:_phoneNum];
            [self.navigationController pushViewController:vc animated:YES];
            [vc release];
        }else{            
            [RCAppDelegate alertWithCustomizeString:model.errorMsg];
        }
    }
   
}


- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if (range.location >= MAXLENGTH) {
        //        textField.text = [textField.text substringToIndex:MAXLENGTH-1];
        return NO;
    }
    return YES;
}



- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self regPress:nil];
    return YES;
}
@end
